<?php
/*
 * Created on Mar 27, 2009
 * author: ANH
 * fileName: IndexController.php
 */
 
 class File_MasterController extends Clu_Controller_Action_Master
{
	/*
	public function init()
	{
		$this->m = new user_Model_User();
	}
	*/
	
	/**
	 *@abstract This action serves as a service for the other modules
	 *  for example, when posting a place, user wants to add a list of files to the place # 1256
	 *  then he can call /en/file/index/upload?c=place&t=image&id=1256&uid=1
	 *  
	 *  This action should present the user with 1 div: 
	 * 		- 1 to upload the file.
	 * 		- 1 div->iframe to display the files already uploaded with this place #id already (starting with 1256)
	 * 		 /public/ustore/$userId/images/place/1256_pic1.jpg
	 * 		 /public/ustore/$userId/images/place/1256_pic2-sanitized-name.jpg
	 * 		Each image is also attached with a "Delete" link to delete the image. then only the iframe is reloaded
	 * 
	 * @see generate_image_copies for how the images are stored
	 * @note: At of 04 May 2009, this targets at uploading images for place module, or user... only
	 *  but it sure can be extended to serve other files
	 * 
	 * 
	 * 
	 */ 
	public function uploadAction()
	{
		//get module name & id here
		$contentType = $this->_request->getParam('c');
		$id = $this->_request->getParam('id');
		$fileType = $this->_request->getParam('t'); 
		$uid = $this->_request->getParam('uid');
		if (!$contentType || !$id || !$fileType)
			die("contentType or id or fileType is not specified. Die!!");
			
		//TODO: check user authorization, if the user is actually responsible for this contentId
		//other wise a user can upload his own shit to his /place/1235_pic.jpg for example even
		//if he did not create place#1235
		//This has to be checked from calling module, not here
		//or user is allowed to edit content
			
		//allowed, now continue
    	$sess = new Zend_Session_Namespace(CLU_NS);
    	$this->viewParams['form'] = new Form_Upload();
   // 	$this->viewParams['form']->cluBuild($contentType, $id, $uid, $fileType, $this->view);
    	
    	$actionUrl = $this->view->hvnUrl(array('module' => 'file', 'action'=>'upload'), 'nocontroller'). '?c='.$contentType.'&id='.$id.'&t='.$fileType.'&uid='.$uid;
        $this->viewParams['form']->cluBuild(array('action' => 'upload', 'action_url' => $actionUrl, 
        												  'contentType' => $contentType,'contentId' => $id,
        												  'fileType' => $fileType, 'uid' =>$uid,
                                                          'userPermissions' => $sess->userPermissions, 
                                                          'language' => $sess->viewLang ));
        
    	$this->viewParams['id'] = $id;
    	$this->viewParams['uid'] = $uid;
    	$this->viewParams['t'] = $fileType;
    	$this->viewParams['c'] = $contentType;
    	if($this->_request->isPost())
		{
			$formData = $this->_request->getPost();
			if ($this->viewParams['form']->isValid($formData) && $fileType == 'image') 
					$this->postImage($contentType, $id, $uid, true);
		}
    	//$iframe = $this->view->render($sess->viewLang . "/account/update-avatar-iframe.phtml");
//    	$this->renderToHolder("index/upload.phtml");
    	//$txt = $this->view->render("commonTheme/nolang/index/upload.phtml");
    	//die_a($this->viewParams['form']);
    	$txt = $this->render("/modules/file/views/scripts/commonTheme/commonLang/common/upload.phtml");
		echo $txt;
	}

	public function imageListAction()
	{
		$contentType = $this->_request->getParam('c');
		$id = $this->_request->getParam('id');
		$fileType = $this->_request->getParam('t'); 
		$userId = $this->_request->getParam('uid');
		
		if (!$contentType || !$id || !$fileType)
			die("contentType or id or fileType is not specified. Die!!");
		//find the directory
		
		$dir = APP_PATH."/public/ufiles/$userId/images/original/$contentType/";
		if(file_exists($dir))
		{
		    $files = scandir($dir);
		    $displayFiles = array();
		    foreach ($files as $f)
		    {
		    	if (strpos ($f, $id ."_") === 0)
		    	{
 		    		$ctime = filectime($dir . $f); 
 		    		$displayFiles[$f] = $ctime;
		    	}
		    }
		    
		    if (count ($displayFiles) > 0)
		    {
			    asort($displayFiles);
			    $this->viewParams['displayFiles'] = $displayFiles;
		    	$this->viewParams['base'] = "/public/ufiles/$userId/images/%s/$contentType/";
    		    $this->viewParams['c'] = $contentType ;
    		    $this->viewParams['id'] = $id ;
    	   	    $this->viewParams['t'] = $fileType ;
    		    $this->viewParams['uid'] = $userId ;
		    	$txt = $this->render("/modules/file/views/scripts/commonTheme/commonLang/common/thumbnail-list.phtml");
		    	echo $txt;
		    }
		    else
		    {
		    	echo "No image in the gallery";
		    }
		}
	    exit();

		/* moved to imageListAction()
		if (file_exists(APP_PATH."/public/ufiles/$id/images/original/avatar/avatar.jpg"))
		{
			$this->view->avatar_image_rand = "/public/ufiles/$id/images/%s/avatar/avatar.jpg?". time();
			$this->view->avatar_image = APP_PATH."/public/ufiles/$id/images/%s/avatar/avatar.jpg";
		}
		*/
	
	}

	public function deleteFileAction()
	{
		$src = $this->_request->getParam('img');
		$tmp = '/^\/public\/ufiles\/(\d+)\/images\/([^\/]*)\/(.*)/';
		
		//cut string, get name file
		preg_match($tmp,$src,$temp);
		$configSizes = array("xxsmall", "xsmall", "small", "medium", "original", "large", "xlarge");
		$source = array("ufiles", "ustore");
		
		foreach ($source as $s)
			foreach ($configSizes as $size)
    		{
    			$file = APP_PATH."/public/$s/$temp[1]/images/$size/$temp[3]";
    			if (file_exists($file))
    				unlink($file);
    		}
		$src = $this->_request->getParam('img');
		$tmp = '/^\/public\/ufiles\/(\d+)\/images\/([^\/]*)\/(.*)/';
		
		//cut string, get name file
		preg_match($tmp,$src,$temp);
	
		$configSizes = array("xxsmall", "xsmall", "small", "medium", "original", "large", "xlarge");
		$source = array("ufiles", "ustore");
		
		foreach ($source as $s)
			foreach ($configSizes as $size)
    		{
    			$file = APP_PATH."/public/$s/$temp[1]/images/$size/$temp[3]";
    			if (file_exists($file))
    				unlink($file);
    		}

		$this->viewParams['c']    = $this->_request->getParam('c') ;
	    $this->viewParams['id']   = $this->_request->getParam('id') ;
   	    $this->viewParams['t']     = $this->_request->getParam('t') ;
	    $this->viewParams['uid'] = $this->_request->getParam('uid') ;
		$txt = $this->render("/modules/file/views/scripts/commonTheme/commonLang/common/view.phtml");
    	echo $txt;
    	die();
	}
	
	public function postImage($contentType, $contentId, $userId, $createWM)
	{
		//require_once APP_PATH."/library/common.php";
		$watermarkDir = APP_PATH."/public/watermark/";

		//see generate_image_copies() @ /library/common.php
		$ustoreDir = APP_PATH."/public/ustore/$userId/images/original/$contentType/";
		if (!file_exists($ustoreDir))
			mkdir($ustoreDir, 0777  , true);

		$ufilesDir = APP_PATH."/public/ufiles/$userId/images/original/$contentType/" ; //just for avatar
		if (!file_exists($ufilesDir))
			mkdir($ufilesDir, 0777  , true);
		$id = $this->_request->getParam('id');
		$adapter= new Zend_File_Transfer_Adapter_Http();

		//normal content type like place#2135 is different from uploading avatar
		if ($contentType == 'avatar')
    	{
    		$originalFilename = "avatar.jpg";
    		$configSizes = array("xxsmall", "xsmall", "small", "medium");
    		$configSizesInPixel = array("30", "75", "100", "260");
    		//delete current images first
    		foreach ($configSizes as $size)
    		{
    			unlink(APP_PATH."/public/ufiles/$userId/images/$size/avatar/avatar.jpg");
    		}
    	}
		else //uploading content is a little different from avatar as there is only 1 avatar per user
		{
    		$extension_path = pathinfo($_FILES['file_upload']['name']);
    		$fileName = $extension_path['filename'];
    		$extension =  $extension_path['extension'];
    		
    		if (empty($extension))
    		{		
    			$mimeType = $_FILES['file_upload']['type'];
    			$extension = explode('/', $mimeType);
    		}
    
    		$saneFileName = SanitizeFileName($fileName);
    		$i = 1;
    		while(file_exists($ustoreDir. $contentId . '_' . $saneFileName . "." . $extension))
    		{
    			$saneFileName = $saneFileName . "_" .$i;
    			$i++;
    		}
    		$originalFilename =  $contentId . '_' . $saneFileName . "." . $extension;
    		//$originalFilename = $contentId . '_' . $saneFileName . "." . $extension
		}
		//now that we have the file name. Let's get it    		    	          	
		try 
		{
			$adapter->addFilter('Rename', array('target' => $ustoreDir. $originalFilename, 'overwrite' => true));
			$adapter->receive();
		}
		catch (Zend_File_Transfer_Exception $e) 
		{
		     $e->getMessage();
		}
		chmod($ustoreDir. $originalFilename, 0666);
		//die_a(array("ustore", $ustoreDir, $saneFileName, $watermarkDir, null, null, $userId, true) );
		if ($contentType == 'avatar')
    		generate_image_copies ("ustore", $ustoreDir, $originalFilename, $watermarkDir, $configSizes, $configSizesInPixel, $userId, false);    	
		else 
		{
			generate_image_copies ("ustore", $ustoreDir,$originalFilename, $watermarkDir, null, null, $userId, false); //with wm
			//die_a(array("ustore", $ustoreDir,$originalFilename, $watermarkDir, null, null, $userId, true));
		}                
	}
		
	
}
?>
